//
//  ViewController.swift
//  openSchema
//
//  Created by QITMAC000647 on 2018/10/30.
//  Copyright © 2018年 NUB8RD6CDW. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var lableId: UILabel!
    @IBOutlet weak var textId: UITextField!
    @IBOutlet weak var labelSchema: UILabel!
    @IBOutlet weak var textUrl: UITextField!
    @IBOutlet weak var submitButton: UIButton!
    @IBOutlet weak var resetButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        textUrl.isAccessibilityElement = true;
        textId.isAccessibilityElement = true;

        textUrl.accessibilityValue = "1urlEdit"
        textId.accessibilityValue = "1idEdit"
        
        lableId.accessibilityIdentifier = "idLabel"
        textId.accessibilityIdentifier = "idEdit"
        labelSchema.accessibilityIdentifier = "schemaLabel"
        textUrl.accessibilityIdentifier  = "urlEdit"
        submitButton.accessibilityIdentifier = "submit"
        resetButton.accessibilityIdentifier = "reset"
        
    
        
        labelSchema.numberOfLines = 0
        
        //设置圆角
        submitButton.layer.cornerRadius = 5
        submitButton.layer.masksToBounds = true
        submitButton.layer.borderWidth = 2
        submitButton.layer.borderColor = UIColor.blue.cgColor
        submitButton.layer.backgroundColor = UIColor.blue.cgColor
        submitButton.setTitleColor(UIColor.white, for: .normal)
        submitButton.addTarget(self, action: #selector(touchUpSubmit), for: .touchUpInside)
        
        resetButton.layer.cornerRadius = 5
        resetButton.layer.masksToBounds = true
        resetButton.layer.borderWidth = 2
        resetButton.layer.borderColor = UIColor.blue.cgColor
        resetButton.layer.backgroundColor = UIColor.blue.cgColor
        resetButton.setTitleColor(UIColor.white, for: .normal)
        resetButton.addTarget(self, action: #selector(touchUpReset), for: .touchUpInside)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    @objc func touchUpSubmit(){
        let idStr : String = textId.text!
        let urlStr : String = textUrl.text!
        var schema : String
        if urlStr.isEmpty{
            schema = readSchema(id: idStr)
        } else {
            schema = urlStr
        }
        if let url = URL(string: schema) {
            //根据iOS系统版本，分别处理
            if #available(iOS 10, *) {
                UIApplication.shared.open(url, options: [:],
                                          completionHandler: {
                                            (success) in
                })
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }
    
    @objc func touchUpReset(){
        textId.text = ""
        textUrl.text = ""
    }
    
    func readSchema(id:String) -> String {
        let schemeData = getRequest(path: "http://hotelxtsurls.beta.qunar.com/xts_schema_txt/hotel_ios_schemas.txt")
        let schemeArray : Array =  schemeData.components(separatedBy: "\n")
        
        for sub in schemeArray{
            let str = sub.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
            if sub.count > 0  && str.count > 0 {
                let infoArray =  sub.components(separatedBy: "|")
                if infoArray[0].caseInsensitiveCompare(id).rawValue == 0 {
                    return infoArray[1]
                }
            }
        }
        return ""
    }
    
    func getRequest(path:String) -> String {
        
        var resStr:String?
        
        //创建URL对象
        let urlString:String = path
        let url = URL(string:urlString)
        
        //创建请求对象
        let request = URLRequest(url: url!)
        let session = URLSession.shared
        let semaphore = DispatchSemaphore(value: 0)
        let dataTask = session.dataTask(with: request,
            completionHandler: {(data, response, error) -> Void in
                if error != nil{
                    print(error!)
                }else{
                    let str = String(data: data!, encoding: String.Encoding.utf8)
                    resStr = str!
                }
                semaphore.signal()
        }) as URLSessionTask
        
        //使用resume方法启动任务
        dataTask.resume()
        _ = semaphore.wait(timeout: DispatchTime.distantFuture)
        print("数据加载完毕！")
    
        return resStr!
        
    }
    
}

